# Basic Python Plugin Example
#
# Author: GizMoCuz
#
"""
<plugin key="XiaomiAirPurifier" name="Xiaomi Air Purifier" author="xuefeng" version="1.0.0" wikilink="http://www.domoticz.com/wiki/plugins/plugin.html" externallink="https://www.google.com/">
    <params>
            <param field="Address" label="Purifier IP" width="200px" required="true" default="192.168.31.48"/>
            <param field="Mode1" label="Refresh (sec)" width="30px" required="true" default="30"/>
    </params>
</plugin>
"""
import sys
import Domoticz
import codecs
from packet.packet import Packet

class PurifierPlugin:
    pm25Unit = 1
    deviceUnit = 2
    humiUnit = 3
    
    def __init__(self):
        #self.var = 123
        return

    def onStart(self):
        Domoticz.Debugging(1)
        Domoticz.Log("onStart called")
        
        if self.pm25Unit not in Devices:
            Domoticz.Device(Name='PM2.5', Unit=self.pm25Unit, TypeName='Custom', Options={"Custom":"1;μg/m³"}, Used=1).Create()
        if self.deviceUnit not in Devices:
            Domoticz.Device(Name='Purifier', Unit=self.deviceUnit, TypeName='Switch', Used=1).Create()
        if self.humiUnit not in Devices:
            Domoticz.Device(Name='Humidity', Unit=self.humiUnit, TypeName='Humidity', Used=1).Create()
	
        self.device = Packet(Parameters["Address"])
        Domoticz.Heartbeat(int(Parameters['Mode1']))

    def onStop(self):
        Domoticz.Log("onStop called")

    def onConnect(self, Connection, Status, Description):
        Domoticz.Log("onConnect called")

    def onMessage(self, Connection, Data):
        Domoticz.Log("onMessage called")

    def onCommand(self, Unit, Command, Level, Hue):
        Domoticz.Log("onCommand called for Unit " + str(Unit) + ": Parameter '" + str(Command) + "', Level: " + str(Level))
        if self.deviceUnit not in Devices:
            Domoticz.Error('Device is required')
            return

        if self.deviceUnit == Unit:
            if 'On' == Command:
                UpdateDevice(Unit, 1, "", -1)
                Domoticz.Debug(str(self.device.sendCmd("set_power", ["on"])))
            elif 'Off' == Command:
                UpdateDevice(Unit, 0, "", -1)
                Domoticz.Debug(str(self.device.sendCmd("set_power", ["off"])))

    def onNotification(self, Name, Subject, Text, Status, Priority, Sound, ImageFile):
        Domoticz.Log("Notification: " + Name + "," + Subject + "," + Text + "," + Status + "," + str(Priority) + "," + Sound + "," + ImageFile)

    def onDisconnect(self, Connection):
        Domoticz.Log("onDisconnect called")

    def onHeartbeat(self):
        Domoticz.Log("onHeartbeat called")
        if self.device is None:
            return
        result = self.device.sendCmd('get_prop', ["power","aqi","humidity", "favorite_level"])
        Domoticz.Debug('result %s' % result)
        if 'on' == result[0] :
            UpdateDevice(self.deviceUnit, 1, "", -1)
        elif 'off' == result[0] :
            UpdateDevice(self.deviceUnit, 0, "", -1)

        UpdateDevice(self.pm25Unit, 0, result[1], -1)
        UpdateDevice(self.humiUnit, result[2], "", -1)
    
    @property
    def isON(self):
        return Devices[self.deviceUnit].nValue == 1

    @property
    def isOFF(self):
        return Devices[self.deviceUnit].nValue == 0

def UpdateDevice(Unit, nValue, sValue, icon):
    # Make sure that the Domoticz device still exists (they can be deleted) before updating it
    if (Unit not in Devices): return
    if (Devices[Unit].nValue != nValue) or (Devices[Unit].sValue != sValue):
        if (icon != -1) and (Devices[Unit].Image != icon):
            Devices[Unit].Update(nValue=nValue, sValue=str(sValue), Image=icon)
        else:
            Devices[Unit].Update(nValue=nValue, sValue=str(sValue))
        Domoticz.Log("Update "+str(nValue)+":'"+str(sValue)+"' ("+Devices[Unit].Name+")")

global _plugin
_plugin = PurifierPlugin()

def onStart():
    global _plugin
    _plugin.onStart()

def onStop():
    global _plugin
    _plugin.onStop()

def onConnect(Connection, Status, Description):
    global _plugin
    _plugin.onConnect(Connection, Status, Description)

def onMessage(Connection, Data):
    global _plugin
    _plugin.onMessage(Connection, Data)

def onCommand(Unit, Command, Level, Hue):
    global _plugin
    _plugin.onCommand(Unit, Command, Level, Hue)

def onNotification(Name, Subject, Text, Status, Priority, Sound, ImageFile):
    global _plugin
    _plugin.onNotification(Name, Subject, Text, Status, Priority, Sound, ImageFile)

def onDisconnect(Connection):
    global _plugin
    _plugin.onDisconnect(Connection)

def onHeartbeat():
    global _plugin
    _plugin.onHeartbeat()

    # Generic helper functions
def DumpConfigToLog():
    for x in Parameters:
        if Parameters[x] != "":
            Domoticz.Debug( "'" + x + "':'" + str(Parameters[x]) + "'")
    Domoticz.Debug("Device count: " + str(len(Devices)))
    for x in Devices:
        Domoticz.Debug("Device:           " + str(x) + " - " + str(Devices[x]))
        Domoticz.Debug("Device ID:       '" + str(Devices[x].ID) + "'")
        Domoticz.Debug("Device Name:     '" + Devices[x].Name + "'")
        Domoticz.Debug("Device nValue:    " + str(Devices[x].nValue))
        Domoticz.Debug("Device sValue:   '" + Devices[x].sValue + "'")
        Domoticz.Debug("Device LastLevel: " + str(Devices[x].LastLevel))
    return
